<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="isParentLoading || isLoading"> </a-spin>
      <div class="leftBlock">
        <div class="titleBox">
          <div class="title">上级语音禁用时段</div>
          <div class="addButton">
            <a-button type="primary" :disabled="isParentLoading" :loading="isParentLoading" @click="getParentData()">
              刷新
            </a-button>
          </div>
        </div>
        <div class="modalContentForm">
          <a-form-model
            :model="parentForm"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <template v-for="(levelOne, index) in parentForm.list">
              <a-card :title="levelOne.organization.name" :key="index">
                <template #extra>
                  <Button
                    type="start"
                    label="使用模板"
                    @click="useTemplate(index)"
                  />
                </template>
                <a-row type="flex" justify="space-between">
                  <a-col :span="24">
                    <a-form-model-item
                      v-for="(levelTwo, index2) in levelOne.chargeIntervalsByTime"
                      :key="levelTwo.key"
                      :label="'时间段' + (index2 + 1)"
                    >
                      <a-range-picker
                        v-model="levelTwo['startTime&endTime']"
                        format="HH:mm:ss"
                        valueFormat="HH:mm:ss"
                        :mode="['time', 'time']"
                        dropdownClassName="rangeTimePicker"
                        style="width: 200px;"
                        disabled
                      >
                      </a-range-picker>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-card>
              <br :key="'br/' + index" />
            </template>
          </a-form-model>
        </div>
      </div>
      <div class="rightBlock">
        <div class="titleBox">
          <div class="title">语音禁用时段</div>
          <div class="addButton">
            <a-button type="primary" :disabled="isLoading" :loading="isLoading" @click="handleEdit()">
              设置
            </a-button>
          </div>
        </div>
        <div class="modalContentForm">
          <a-form-model
            ref="formRef"
            :model="form"
            :rules="rules"
            :label-col="{ span: 4 }"
            :wrapper-col="{ span: 20 }"
          >
            <a-card :title="form.organization.name">
              <a-row type="flex" justify="space-between" >
                <a-col :span="24">
                  <a-form-model-item
                    v-for="(domain, index) in form.chargeIntervalsByTime"
                    :key="domain.key"
                    :label="'时间段' + (index + 1)"
                    :prop="'chargeIntervalsByTime.' + index + '.startTime&endTime'"
                    :rules="{
                      type: 'array',
                      required: true,
                      message: '请选择时间段' + (index + 1),
                      trigger: 'change'
                    }"
                  >
                    <a-range-picker
                      v-model="domain['startTime&endTime']"
                      format="HH:mm:ss"
                      valueFormat="HH:mm:ss"
                      :showTime="{
                        hideDisabledOptions: true,
                        defaultOpenValue: moment('00:00:00', 'HH:mm:ss')
                      }"
                      :mode="['time', 'time']"
                      :placeholder="['开始时间', '结束时间']"
                      dropdownClassName="rangeTimePicker"
                      style="width: 200px;"
                    >
                    </a-range-picker>
                    <Button
                      type="stop"
                      v-if="form.chargeIntervalsByTime.length > 1"
                      :disabled="form.chargeIntervalsByTime.length === 1"
                      label="删除时间段"
                      @click="removeDomain(form.chargeIntervalsByTime, domain)"
                    />
                  </a-form-model-item>
                </a-col>
                <a-col :span="12">
                  <Button type="search" label="增加时间段" @click="addDomain"></Button>
                  <div style="width:100%;height: 24px"></div>
                </a-col>
              </a-row>
            </a-card>
          </a-form-model>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import {
  listDisableVoiceTimes,
  createDisableVoiceTime
} from '@/api/api';
import moment from 'moment';
import Input from '@/components/typicalControl/Input';
import treeSelect from '@/components/typicalControl/treeSelect';
import Button from '@/components/typicalControl/button';
import { frontToAfterTransformation } from '@/utils/tool';
export default {
  name: 'UserTemplate',
  components: {
    Input: Input,
    Button: Button,
    treeSelect: treeSelect
  },
  data() {
    return {
      isParentLoading: false,
      isLoading: false,
      parentForm: {
        list: []
      },
      form: {
        organization: {
          name: this.$store.state.user.info.organization.name,
          id: this.$store.state.user.info.organization.id
        },
        chargeIntervalsByTime: [
          {
            'startTime&endTime': [],
            key: 1
          }
        ],
        isEnable: 1,
        isSystem: 0
      },
      rules: {},
      checkTimeIntervalRule: [
        {
          parent: 'chargeIntervalsByTime',
          attribute: 'startTime&endTime'
        }
      ],
      oMapping: {
        isReverse: false,
        startTime: 'startTime&endTime'
      }
    };
  },
  created() {
    this.getParentData();
    this.getCurrentData();
  },
  mounted() {
  },
  methods: {
    moment,
    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        organization: {
          name: this.$store.state.user.info.organization.name,
          id: this.$store.state.user.info.organization.id
        },
        chargeIntervalsByTime: [],
        isEnable: 1,
        isSystem: 0
      };
    },
    /**
     * [getParentData 获取父级的数据]
     * @return {[type]}             [description]
     */
    getParentData() {
      this.isParentLoading = true;
      this.parentForm.list = [];
      listDisableVoiceTimes({ searchDataRang: '2' }).then(res => {
        if (res.data) {
          var levelOne, levelTwo, obj;
          levelOne = res.data;
          for (var i = 0; i < levelOne.length; i++) {
            obj = {
              organization: {
                name: levelOne[i].organization.name,
                id: levelOne[i].organization.id
              },
              chargeIntervalsByTime: []
            };
            levelTwo = levelOne[i].listTimeRang ? levelOne[i].listTimeRang : [];
            for (var j = 0; j < levelTwo.length; j++) {
              obj.chargeIntervalsByTime.push({
                'startTime&endTime': [levelTwo[j].startTime, levelTwo[j].endTime],
                key: i + '-' + j
              });
            }
            this.parentForm.list.push(obj);
          }
        }
      }).finally(() => {
        this.isParentLoading = false;
      });
    },
    /**
     * [useTemplate 使用模板到当前数据]
     * @param  {[type]} index [模板列表数组序号]
     * @return {[type]}       [description]
     */
    useTemplate(index) {
      const useTemplateData = this.parentForm.list[index].chargeIntervalsByTime;
      this.form.chargeIntervalsByTime = [];
      for (var i = 0; i < useTemplateData.length; i++) {
        this.form.chargeIntervalsByTime.push(useTemplateData[i]);
      }
    },
    /**
     * [getCurrentData 获取当前的数据]
     * @return {[type]}             [description]
     */
    getCurrentData() {
      this.isLoading = true;
      listDisableVoiceTimes({ searchDataRang: '3' }).then(res => {
        if (res.data) {
          this.form = this.initializationForm();
          if (res.data[0].listTimeRang && res.data[0].listTimeRang.length > 0) {
            for (var i = 0; i < res.data[0].listTimeRang.length; i++) {
              this.form.chargeIntervalsByTime.push({
                'startTime&endTime': [ res.data[0].listTimeRang[i].startTime, res.data[0].listTimeRang[i].endTime ],
                key: i
              });
            }
          } else {
            this.form.chargeIntervalsByTime.push({
              'startTime&endTime': [],
              key: 1
            });
          }
        }
      }).finally(() => {
        this.isLoading = false;
      });
    },

    /**
     * [handleEdit 提交]
     * @return {[type]}     [description]
     */
    handleEdit() {
      if (this.isTimeIntervalOverlap(this.form, this.checkTimeIntervalRule)) {
        return false;
      }
      this.$refs.formRef.validate(valid => {
        if (valid) {
          const prepareJson = {};
          this.oMapping.isReverse = false;
          frontToAfterTransformation(prepareJson, this.form, this.oMapping);
          var list = [];
          var obj;
          for (var i = 0; i < prepareJson.chargeIntervalsByTime.length; i++) {
            obj = {
              organization: {
                name: this.$store.state.user.info.organization.name,
                id: this.$store.state.user.info.organization.id
              },
              startTime: prepareJson.chargeIntervalsByTime[i].startTime,
              endTime: prepareJson.chargeIntervalsByTime[i].endTime
            };
            list.push(obj);
          }
          this.isLoading = true;
          createDisableVoiceTime({ body: list })
            .then(res => {
              this.$message.success(res.message);
            })
            .finally(() => {
              this.isLoading = false;
            });
        }
      });
    },
    // 动态表单方法
    /**
     * [removeDomain 公共删除]
     * @param  {[type]} parent [所在数组]
     * @param  {[type]} item   [当前数据]
     * @return {[type]}        [description]
     */
    removeDomain(parent, item) {
      const index = parent.indexOf(item);
      if (index !== -1) {
        parent.splice(index, 1);
      }
    },
    /**
     * [addDomain 增加时间区间]
     */
    addDomain() {
      this.form.chargeIntervalsByTime.push({
        'startTime&endTime': [],
        key: Date.now()
      });
    },
    /**
     * [isTimeIntervalOverlap 是否时间区间重叠（arr格式时间）]
     * @param  {[type]}  obj   [校验对象]
     * @param  {[type]}  aRule [校验规则]
     * @return {Boolean}       [是否]
     */
    isTimeIntervalOverlap(obj, aRule) {
      var aParent, i, j, aFlatten, temporaryObj, k, time1, time2, time3, time4;
      aFlatten = [];
      for (i = 0; i < aRule.length; i++) {
        aParent = obj[aRule[i].parent];
        for (j = 0; j < aParent.length; j++) {
          if (aParent[j][aRule[i].attribute].length < 2) {
            // console.log('isTimeIntervalOverlap 时间区间位数不足！');
            // 有必填去校验时间为空
            return false;
          }
          temporaryObj = {};
          temporaryObj.num = j + 1;
          temporaryObj.a = aParent[j][aRule[i].attribute][0];
          temporaryObj.b = aParent[j][aRule[i].attribute][1];
          aFlatten.push(temporaryObj);
        }
        for (j = 0; j < aFlatten.length; j++) {
          for (k = 0; k < aFlatten.length; k++) {
            // 跳过自身比较
            if (k === j) {
              continue;
            }
            // https://ask.csdn.net/questions/1092563
            // 不重叠的规则是：区间A的最大值小于区间B的最小值，或区间A的最小值大于区间B的最大值
            time1 = this.timeToSec(aFlatten[j].a);
            time2 = this.timeToSec(aFlatten[j].b);
            time3 = this.timeToSec(aFlatten[k].a);
            time4 = this.timeToSec(aFlatten[k].b);
            if (!(time2 < time3 || time1 > time4)) {
              const index1 = j + 1;
              const index2 = k + 1;
              this.$message.error('时间段' + index1 + ' 与 时间段' + index2 + ' 重叠');
              return true;
            }
          }
        }
      }
      return false;
    },
    /**
     * [timeToSec 小时分秒转换成秒]
     * @param  {[type]} time [小时分秒]
     * @return {[type]}      [秒]
     */
    timeToSec(time) {
      var result = '';
      if (time && time !== 0) {
        var arr = time.split(':');
        var hour = Number(arr[0]) * 60 * 60;
        var min = Number(arr[1]) * 60;
        var sec = Number(arr[2]);
        result = hour + min + sec;
      }
      return result;
    }
  }
};
</script>

<style scoped>
  .Role {
    width: 100%;
    height: calc(100vh - 150px);
    position: relative;
  }
  .Role .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .leftBlock{
    width: 49%;
    height: calc(100vh - 150px);
    float: left;
    background: #fff;
    overflow: auto;
    border-radius: 5px;
  }
  .rightBlock{
    float: right;
    width: calc(51% - 10px);
    height: calc(100vh - 150px);
    background: #fff;
    overflow: auto;
    border-radius: 5px;
  }
  .titleBox{
    padding: 0 20px;
    width: 100%;
    height: 64px;
    display: flex;
    align-items: center;
  }
  .titleBox .title{
    font-size: 18px;
    font-weight: 550;
    display: flex;
    align-items: center;
  }
  .titleBox .addButton {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
  .modalContentForm{
    padding: 20px;
    height: calc(100vh - 240px);
    overflow: auto;
  }
</style>
